import Formation
import Util
import Configurable
import ConfigParser
import os.path

class Level(Configurable.Configurable):
   runtime_vars = ('formation_number',)

   __slots__ = ('backgroundobjects',
                'backgrounddensities',
                'shopitems',
                'formations') + runtime_vars
   
   def __init__(self, formations=list(), shopitems=list(), backgroundobjects=list(), backgrounddensities=None, **args):
      if backgrounddensities is None:
         backgrounddensities = [0.0 for i in backgroundobjects]
      locals().update(args)
      Configurable.Configurable.__init__(self, locals())
      self.backgroundobjects = list()
      for b in backgroundobjects:
         self.backgroundobjects.append(Util.load_image(b, colorkey=(0,0,0))[0])
      self.formation_number = 0
                
   @classmethod
   def many_from_file(cls, config_file):
      cf = ConfigParser.RawConfigParser()
      cf.read(config_file)
      sections = list()
      for line in open(config_file, 'r').readlines():
         l = line.strip()
         if l.startswith('[') and l.endswith(']'):
            sections.append(l[1:-1])
      forms_list = [[] for i in range(0, len(sections)-1)]
      level = None
      i = 0
      for section in sections:
         if section == 'General':
            items = cf.items(section)
            items.append(['name', os.path.splitext(config_file)[0]])
            level = cls.from_file(items)
         else:
            items = cf.items(section)
            items.extend([['name', section], ['order', i]])
            formation = Formation.Formation.from_file(items)
            forms_list[i] = formation
            i += 1
      if level is None:
         Util.error("Level information not provided in %s." % config_file)
      level['formations'] = forms_list
      return level

   def next_formation(self):
      if self.formation_number < len(self.formations):
         f = Configurable.instantiate(self.formations[self.formation_number])
         self.formation_number += 1
         return f
      else:
         return None

   def next_formation_cond(self):
      return self.formations[self.formation_number].get('when', 0)
